//
//  HTTPClient.swift
//  sinaWeibo
//
//  Created by liii on 16/8/6.
//  Copyright © 2016年 liii. All rights reserved.
//

import UIKit
import AFNetworking

// 测试环境
let hostname = "https://api.weibo.com/"
// 线上环境
//let hostname = "https://api.weibo.com/"

// 自定义错误信息, 反转域名
private let domain = "com.baidu.error"

enum httpMethods: String {
    case POST = "POST"
    case GET = "GET"
}

class HTTPClient: AFHTTPSessionManager {

    // 1.单例对象(伪单例)
    static let sharedClient: HTTPClient = {
        
        let url = NSURL(string: hostname)
        let afn = HTTPClient(baseURL: url)
        afn.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return afn
    }()
    
    // 2.网络请求核心方法
    func requestJSONDict(method: httpMethods, urlString: String, parameters: [String : AnyObject], finished: (dict: [String : AnyObject]?, error: NSError?) -> ()) {
        
        print(urlString)
        // 选择求情方法
        if method == .POST {
            
            // 发送POST请求
            POST(urlString, parameters: parameters, success: { (_, result) -> Void in
                
                // 请求成功, 过滤数据错误
                guard let dict = result as? [String : AnyObject] else {
                    
                    print("数据格式错误")
                    // 出现错误, 返回错误信息(自定义)
                    let myError = NSError(domain: domain, code: 10001, userInfo: [NSLocalizedDescriptionKey : "数据结构错误"])
                    finished(dict: nil, error: myError)
                    return
                }
                
                // 没有错误, 回调数据
                finished(dict: dict, error: nil)
                
                }, failure: { (_, error) -> Void in
                    
                    // 请求失败, 返回错误信息
                    finished(dict: nil, error: error)
             })
            
        } else {
            
            // 发送GET请求
            GET(urlString, parameters: parameters, success: { (_, result) -> Void in
                
                // 请求成功, 过滤数据错误
                guard let dict = result as? [String : AnyObject] else {
                    
                    print("数据格式错误")
                    // 出现错误, 返回错误信息(自定义)
                    let myError = NSError(domain: domain, code: 10001, userInfo: [NSLocalizedDescriptionKey : "数据结构错误"])
                    finished(dict: nil, error: myError)
                    return
                }
                
                // 没有错误, 回调数据
                finished(dict: dict, error: nil)
                
                }, failure: { (_, error) -> Void in
                    
                    // 请求失败, 返回错误信息
                    finished(dict: nil, error: error)
            })
        }
    }
}
